//
//  WebVIewViewController.swift
//  iot-webview
//
//  Created by hech on 2024/11/6.
//

import UIKit
import WebKit

class WebViewViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!

    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        // 配置 WKWebViewConfiguration
        let webConfiguration = WKWebViewConfiguration()
        
        // 初始化 WKWebView
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        // 添加到视图
        view.addSubview(webView)
        
        // 设置 Webview 的约束 (这里全屏显示)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        
        // 加载网页
        let urlString = "https://api.ximalaya.com/gatekeeper/iot-cloud-content?appKey=ec8b0902de014b1590b3623b910fb732&phone=19166298621#/"
    
        if let url = URL(string: urlString) {
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }
    

   
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if let urlString = webView.url?.absoluteString, urlString.contains("trade-v3/settlement/orderview") {
            let js = "document.querySelector('.header').style.display='none'; document.querySelector('.view').style.paddingTop='8px';"
            webView.evaluateJavaScript(js, completionHandler: nil)
        }

        if let urlString = webView.url?.absoluteString, urlString.contains("cashier2/mcashier/show") {
            let js = "document.querySelector('.header').style.display='none'; document.querySelector('.view').style.paddingTop='8px';"
            webView.evaluateJavaScript(js, completionHandler: nil)
        }
    }
    
    // H5 拉起微信支付
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        if let url = navigationAction.request.url, url.scheme == "weixin" {
            print("Navigation request URL: \(url.absoluteString)")
            UIApplication.shared.open(url)
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }

}
